package com.sxm.yiwei.tools;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.sxm.yiwei.R;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.x;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

/**
 *  ImgSwitcherActivity 图片查看器（异步加载图片）
 */
public class ImgSwitcherActivity extends Activity implements ViewSwitcher.ViewFactory, View.OnTouchListener {
    /**
     * ImagaSwitcher 的引用
     *
     */
    private ImageSwitcher mImageSwitcher;
    /**
     * 图片id数组
     */
    private int[] imgIds;
    /**
     * 当前选中的图片id序号
     */
    private int currentPosition;
    /**
     * 按下点的X坐标
     */
    private float downX;
    /**
     * 装载点点的容器
     */
    private LinearLayout linearLayout;
    /**
     * 点点数组
     */
    private ImageView[] tips;
    private ImageView gou;
    private ArrayList<String> imgs1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img_switcher);
        gou = (ImageView) findViewById(R.id.gou);
        gou.setAlpha(0.6f);
        gou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImgSwitcherActivity.this.finish();
            }
        });
        currentPosition = getIntent().getIntExtra("position", 0);
        imgs1 = getIntent().getStringArrayListExtra("imgs");
        GetImageTask task = new GetImageTask(ImgSwitcherActivity.this);
        task.execute(InternetAddressUtis.IMG_URL+imgs1.get(currentPosition));

        //实例化ImageSwitcher
        mImageSwitcher  = (ImageSwitcher) findViewById(R.id.imageSwitcher1);
        //设置Factory
        mImageSwitcher.setFactory(this);
        //设置OnTouchListener，我们通过Touch事件来切换图片
        mImageSwitcher.setOnTouchListener(this);

        linearLayout = (LinearLayout) findViewById(R.id.viewGroup);

        tips = new ImageView[imgs1.size()];
        for(int i = 0; i< imgs1.size(); i++){
            ImageView mImageView = new ImageView(this);
            tips[i] = mImageView;
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            layoutParams.rightMargin = 3;
            layoutParams.leftMargin = 3;

            mImageView.setBackgroundResource(R.mipmap.y2);
            linearLayout.addView(mImageView, layoutParams);
        }

        //这个我是从上一个界面传过来的，上一个界面是一个GridView
        mImageSwitcher.setImageURI(Uri.parse(InternetAddressUtis.IMG_URL+imgs1.get(currentPosition)));
        setImageBackground(currentPosition);

    }


    private void setImageBackground(int currentPosition) {

        for(int i=0; i<tips.length; i++){
            if(i == currentPosition){
                tips[i].setBackgroundResource(R.mipmap.y1);
            }else{
                tips[i].setBackgroundResource(R.mipmap.y2);
            }
        }
    }

    @Override
    public View makeView() {
        final ImageView i = new ImageView(this);
        i.setBackgroundColor(0xff000000);
        //i.setScaleType(ImageView.ScaleType.CENTER_CROP);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
        return i ;
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:{
                //手指按下的X坐标
                downX = event.getX();
                break;
            }
            case MotionEvent.ACTION_UP:{
                float lastX = event.getX();
                //抬起的时候的X坐标大于按下的时候就显示上一张图片
                if(lastX > downX){
                    if(currentPosition > 0){
                        //设置动画，这里的动画比较简单，不明白的去网上看看相关内容
                        mImageSwitcher.setInAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.left_in));
                        mImageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.right_out));
                        currentPosition --;
                        GetImageTask task = new GetImageTask(ImgSwitcherActivity.this);
                        task.execute(InternetAddressUtis.IMG_URL+imgs1.get(currentPosition));

                        setImageBackground(currentPosition);
                    }else{
                        Toast.makeText(getApplication(), "已经是第一张", Toast.LENGTH_SHORT).show();
                    }
                }

                if(lastX < downX){
                    if(currentPosition < imgs1.size() - 1){
                        mImageSwitcher.setInAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.right_in));
                        mImageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getApplication(), R.anim.left_out));
                        currentPosition ++ ;
                        GetImageTask task = new GetImageTask(ImgSwitcherActivity.this);
                        task.execute(InternetAddressUtis.IMG_URL+imgs1.get(currentPosition));
                        mImageSwitcher.setImageURI(Uri.parse(imgs1.get(currentPosition)));
                        setImageBackground(currentPosition);
                    }else{
                        Toast.makeText(getApplication(), "到了最后一张", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            break;
        }

        return true;
    }

    /**
     *  异步 加载图片
     */
    class GetImageTask extends AsyncTask<String, Integer, Bitmap> {
        private Activity mActivity;
        public GetImageTask(Activity activity) {
            mActivity = activity;
        }
        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap;
            try {
                URL picUrl = new URL(params[0]);
                HttpURLConnection urlConn;
                urlConn = (HttpURLConnection) picUrl.openConnection();
                urlConn.setConnectTimeout(5000);
                urlConn.setReadTimeout(5000);
                InputStream is = urlConn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();
            } catch (Exception e) {
                return null;
            }
            return bitmap;
        }


        protected void onProgressUpdate(Integer... progress) {
        }

        /**
         * 后台任务执行完之后被调用，在UI线程执行
         */
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                Drawable drawable = new BitmapDrawable(result);
                mImageSwitcher.setImageDrawable(drawable);
            } else {
                //获取图片网络失败
                Toast.makeText(mActivity, "图片不存在", Toast.LENGTH_SHORT).show();
            }

        }

        /**
         * 在 doInBackground(Params...)之前被调用，在UI线程执行
         */
        protected void onPreExecute() {

        }

        /**
         * 在UI线程执行
         */
        protected void onCancelled() {
        }
    }

}
